package xyz.xdxx152.elasticdemo.service;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import xyz.xdxx152.elasticdemo.config.ElasticSearchConfig;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class ElasticSearchService<T> {

    @Autowired
    RestHighLevelClient restHighLevelClient;

//    索引一条数据
    public void indexData(T data) throws IOException {
//        索引数据请求
        IndexRequest indexRequest = new IndexRequest("users","_doc","1");

        String jsonString = JSON.toJSONString(data);
        indexRequest.source(jsonString, XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);

//      打印响应数据
        System.out.println(indexResponse);
    }

//    删除一条数据
    public void deleteData(String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("users","_doc",id);
        DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, ElasticSearchConfig.COMMON_OPTIONS);
//      打印响应数据
        System.out.println(deleteResponse);
    }

//  通过id获取一条数据
    public void getDataByID(String id) throws IOException {
        GetRequest getRequest = new GetRequest("users", "_doc", id);
        GetResponse documentFields = restHighLevelClient.get(getRequest, ElasticSearchConfig.COMMON_OPTIONS);
        System.out.println(documentFields);
    }

    // 根据id来更新数据
    public void updateById(String id) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("users", "_doc", id);
        Map<String,Object> map = new HashMap<>();
        map.put("name","胡宇轩");
        UpdateRequest doc = updateRequest.doc(map);
        UpdateResponse update = restHighLevelClient.update(doc, ElasticSearchConfig.COMMON_OPTIONS);
        System.out.println(update);
    }

}
